<template>
  <div class="card-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>银行卡管理</h2>
      <p>管理系统中的所有银行卡信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="银行卡号">
          <el-input 
            v-model="searchForm.cardid" 
            placeholder="请输入银行卡号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="持卡人">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入持卡人姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input 
            v-model="searchForm.pid" 
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="卡片状态">
          <el-select v-model="searchForm.isreportloss" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="正常" value="否" />
            <el-option label="已挂失" value="是" />
          </el-select>
        </el-form-item>
        <el-form-item label="开卡时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增银行卡
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出CSV
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 银行卡列表 -->
    <el-card class="table-card">
      <el-table 
        :data="cardList" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="cardid" label="银行卡号" width="180">
          <template #default="{ row }">
            {{ formatCardNumber(row.cardid) }}
          </template>
        </el-table-column>
        <el-table-column prop="customername" label="持卡人" width="120" />
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="{ row }">
            <span class="balance-amount">¥{{ Number(row.balance).toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="curid" label="币种" width="80" />
        <el-table-column prop="savingid" label="存款类型ID" width="120" />
        <el-table-column prop="isreportloss" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isreportloss === '否' ? 'success' : 'danger'" size="small">
              {{ row.isreportloss === '否' ? '正常' : '已挂失' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="opendate" label="开卡时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.opendate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="warning" size="small" @click="handleChangePassword(row)">
              <el-icon><Key /></el-icon>
              改密
            </el-button>
            <el-button 
              :type="row.isreportloss === '否' ? 'danger' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              <el-icon><Lock /></el-icon>
              {{ row.isreportloss === '否' ? '挂失' : '解挂' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增银行卡对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增银行卡"
      width="500px"
      @close="handleAddDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="币种" prop="curid">
          <el-select v-model="addForm.curid" placeholder="请选择币种" style="width: 100%">
            <el-option label="人民币" value="RMB" />
            <el-option label="美元" value="USD" />
            <el-option label="欧元" value="EUR" />
          </el-select>
        </el-form-item>
        <el-form-item label="存款类型" prop="savingid">
          <el-select v-model="addForm.savingid" placeholder="请选择存款类型" style="width: 100%">
            <el-option 
              v-for="deposit in depositTypes" 
              :key="deposit.savingid" 
              :label="deposit.savingtype" 
              :value="deposit.savingid" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开户金额" prop="openmoney">
          <el-input-number 
            v-model="addForm.openmoney" 
            :min="1" 
            :precision="2" 
            placeholder="请输入开户金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="pid">
          <el-input v-model="addForm.pid" placeholder="请输入持卡人身份证号" maxlength="18" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改银行卡密码"
      width="400px"
      @close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="银行卡号">
          <el-input :value="formatCardNumber(selectedCard?.cardid)" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入6位数字密码"
            maxlength="6"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            maxlength="6"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 银行卡详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="银行卡详情"
      width="600px"
    >
      <div v-if="selectedCard" class="card-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="银行卡号">
            {{ formatCardNumber(selectedCard.cardid) }}
          </el-descriptions-item>
          <el-descriptions-item label="持卡人">
            {{ selectedCard.customername }}
          </el-descriptions-item>
          <el-descriptions-item label="余额">
            <span class="balance-amount">¥{{ Number(selectedCard.balance).toLocaleString() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="币种">
            {{ selectedCard.curid }}
          </el-descriptions-item>
          <el-descriptions-item label="存款类型ID">
            {{ selectedCard.savingid }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedCard.isreportloss === '否' ? 'success' : 'danger'">
              {{ selectedCard.isreportloss === '否' ? '正常' : '已挂失' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开卡时间">
            {{ formatDate(selectedCard.opendate) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  View,
  Key,
  Lock,
  Delete,
  Download
} from '@element-plus/icons-vue'
import { adminCardApi } from '@/api/card'
import { adminDepositApi } from '@/api/deposit'
import { CSVExporter, cardExportColumns } from '@/utils/csvExport'

export default {
  name: 'CardManage',
  components: {
    Search,
    Refresh,
    Plus,
    View,
    Key,
    Lock,
    Delete,
    Download
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const exportLoading = ref(false)
    const addDialogVisible = ref(false)
    const passwordDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const addFormRef = ref(null)
    const passwordFormRef = ref(null)
    const selectedCard = ref(null)

    // 搜索表单
    const searchForm = reactive({
      cardid: '',
      username: '',
      pid: '',
      isreportloss: ''
    })

    // 日期范围
    const dateRange = ref([])

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 银行卡列表
    const cardList = ref([])

    // 存款类型列表
    const depositTypes = ref([])

    // 新增表单
    const addForm = reactive({
      curid: 'RMB',
      savingid: null,
      openmoney: 1,
      pid: ''
    })

    // 密码表单
    const passwordForm = reactive({
      newPassword: '',
      confirmPassword: ''
    })

    // 新增表单验证规则
    const addRules = {
      curid: [
        { required: true, message: '请选择币种', trigger: 'change' }
      ],
      savingid: [
        { required: true, message: '请选择存款类型', trigger: 'change' }
      ],
      openmoney: [
        { required: true, message: '请输入开户金额', trigger: 'blur' },
        { type: 'number', min: 1, message: '开户金额不能少于1元', trigger: 'blur' }
      ],
      pid: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的18位身份证号', trigger: 'blur' }
      ]
    }

    // 密码表单验证规则
    const passwordRules = {
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '密码必须是6位数字', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 获取银行卡列表
    const fetchCards = async () => {
      loading.value = true
      try {
        const queryData = {
          page: pagination.current,
          pageSize: pagination.size,
          ...searchForm
        }

        const [begin, end] = dateRange.value || []
        const response = await adminCardApi.pageCard(queryData, begin, end)
        
        if (response.code === 0) {
          cardList.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.msg || '获取银行卡列表失败')
        }
      } catch (error) {
        console.error('获取银行卡列表失败:', error)
        ElMessage.error('获取银行卡列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取存款类型列表
    const fetchDepositTypes = async () => {
      try {
        const response = await adminDepositApi.pageDeposit({ page: 1, pageSize: 100 })
        if (response.code === 0) {
          depositTypes.value = response.data.records || []
        }
      } catch (error) {
        console.error('获取存款类型失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchCards()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        cardid: '',
        username: '',
        pid: '',
        isreportloss: ''
      })
      dateRange.value = []
      pagination.current = 1
      fetchCards()
    }

    // 新增
    const handleAdd = () => {
      resetAddForm()
      addDialogVisible.value = true
    }

    // 查看详情
    const handleView = async (row) => {
      try {
        const response = await adminCardApi.getCard(row.cardid)
        if (response.code === 0) {
          selectedCard.value = response.data
          detailDialogVisible.value = true
        } else {
          ElMessage.error(response.msg || '获取银行卡详情失败')
        }
      } catch (error) {
        console.error('获取银行卡详情失败:', error)
        ElMessage.error('获取银行卡详情失败')
      }
    }

    // 修改密码
    const handleChangePassword = (row) => {
      selectedCard.value = row
      resetPasswordForm()
      passwordDialogVisible.value = true
    }

    // 切换状态（挂失/解挂）
    const handleToggleStatus = async (row) => {
      const action = row.isreportloss === '否' ? '挂失' : '解挂'
      const newStatus = row.isreportloss === '否' ? '是' : '否'
      
      try {
        await ElMessageBox.confirm(
          `确定要${action}银行卡 "${formatCardNumber(row.cardid)}" 吗？`,
          `${action}确认`,
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await adminCardApi.changeStatus({
          cardid: row.cardid,
          isreportloss: newStatus
        })

        if (response.code === 0) {
          ElMessage.success(`${action}成功`)
          fetchCards()
        } else {
          ElMessage.error(response.msg || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error(`${action}失败:`, error)
          ElMessage.error(`${action}失败`)
        }
      }
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除银行卡 "${formatCardNumber(row.cardid)}" 吗？此操作不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await adminCardApi.deleteCard(row.cardid)
        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchCards()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除银行卡失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 提交新增
    const handleAddSubmit = async () => {
      if (!addFormRef.value) return

      try {
        await addFormRef.value.validate()
        submitLoading.value = true

        const response = await adminCardApi.addCard(addForm)
        if (response.code === 0) {
          ElMessage.success('新增成功')
          addDialogVisible.value = false
          fetchCards()
        } else {
          ElMessage.error(response.msg || '新增失败')
        }
      } catch (error) {
        console.error('新增银行卡失败:', error)
        ElMessage.error('新增失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 提交密码修改
    const handlePasswordSubmit = async () => {
      if (!passwordFormRef.value) return

      try {
        await passwordFormRef.value.validate()
        submitLoading.value = true

        const response = await adminCardApi.changePwd({
          cardid: selectedCard.value.cardid,
          newpassword: passwordForm.newPassword
        })

        if (response.code === 0) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error(response.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 重置新增表单
    const resetAddForm = () => {
      Object.assign(addForm, {
        curid: 'RMB',
        savingid: null,
        openmoney: 1,
        pid: ''
      })
      if (addFormRef.value) {
        addFormRef.value.clearValidate()
      }
    }

    // 重置密码表单
    const resetPasswordForm = () => {
      Object.assign(passwordForm, {
        newPassword: '',
        confirmPassword: ''
      })
      if (passwordFormRef.value) {
        passwordFormRef.value.clearValidate()
      }
    }

    // 对话框关闭处理
    const handleAddDialogClose = () => {
      resetAddForm()
    }

    const handlePasswordDialogClose = () => {
      resetPasswordForm()
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      fetchCards()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      fetchCards()
    }

    // 工具函数
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    const formatIdCard = (idCard) => {
      if (!idCard) return ''
      return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3')
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleDateString('zh-CN')
    }

    // 导出CSV
    const handleExport = async () => {
      if (cardList.value.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }

      try {
        exportLoading.value = true
        CSVExporter.exportToCSV(cardList.value, cardExportColumns, '银行卡管理报表')
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败: ' + error.message)
      } finally {
        exportLoading.value = false
      }
    }

    // 初始化
    onMounted(() => {
      fetchCards()
      fetchDepositTypes()
    })

    return {
      loading,
      submitLoading,
      addDialogVisible,
      passwordDialogVisible,
      detailDialogVisible,
      addFormRef,
      passwordFormRef,
      selectedCard,
      searchForm,
      dateRange,
      pagination,
      cardList,
      depositTypes,
      addForm,
      passwordForm,
      addRules,
      passwordRules,
      handleSearch,
      handleReset,
      handleAdd,
      handleView,
      handleChangePassword,
      handleToggleStatus,
      handleDelete,
      handleAddSubmit,
      handlePasswordSubmit,
      handleAddDialogClose,
      handlePasswordDialogClose,
      handleSizeChange,
      handleCurrentChange,
      formatCardNumber,
      formatIdCard,
      formatDateTime,
      formatDate,
      exportLoading,
      handleExport
    }
  }
}
</script>

<style scoped>
.card-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.balance-amount {
  font-weight: bold;
  color: #67c23a;
}

.card-detail {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}
</style> 